package com.thanhnx.tlg1;

import java.text.DecimalFormat;
import java.util.ArrayList;

import net.bgreco.DirectoryPicker;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {
	private ProgressBar loading_bar;
	private LinearLayout layout;
	private RelativeLayout rl_root;

	private LoadingAsyncTask loading;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		final int ROW_HEIGHT = 40;
		final int COL_WIDTH = 80;
		final int NUM_COLS = 36;
		final int NUM_ROWS = 25;

		String[] cols = new String[NUM_COLS];
		String[] rows = new String[NUM_ROWS];
		String[][] data = new String[NUM_ROWS][NUM_COLS];
		DecimalFormat twoPlaces = new DecimalFormat("0.00");

		// Set up data[][] and rows[], cols[]
		for (int i = 0; i < NUM_ROWS; i++) {
			rows[i] = "" + i;
		}
		for (int i = 0; i < NUM_COLS; i++) {
			cols[i] = numToColumn(i);
		}
		for (int i = 0; i < NUM_ROWS; i++) {
			for (int j = 0; j < NUM_COLS; j++) {
				data[i][j] = "";// twoPlaces.format(Math.random() * 1000);
			}
		}

		// loading_bar = (ProgressBar) findViewById(R.id.loading);
		loading = new LoadingAsyncTask();
		loading.execute();

		// setup left column with row labels
		LinkedScrollView lsvLeftCol = new LinkedScrollView(this);
		// LinkedScrollView lsvLeftColA = new LinkedScrollView(this);

		lsvLeftCol.setVerticalScrollBarEnabled(false); // this one will look
		// lsvLeftColA.setVerticalScrollBarEnabled(false); // this one will look
		// wrong
		TableLayout tlLeftCol = new TableLayout(this);
		// TableLayout tlLeftColA = new TableLayout(this);
		TableLayout.LayoutParams tlLeftColParams = new TableLayout.LayoutParams();
		tlLeftColParams.width = COL_WIDTH / 2;
		tlLeftCol.setLayoutParams(tlLeftColParams);
		// tlLeftColA.setLayoutParams(tlLeftColParams);
		for (int i = -1; i < rows.length; i++) {
			TableRow tr = new TableRow(this);
			tr.setMinimumHeight(ROW_HEIGHT);
			tr.setGravity(Gravity.CENTER);
			if (i % 2 == 0) {
				tr.setBackgroundResource(R.color.header_bg);
			}
			TextView tv = new TextView(this);
			if (i >= 0) // -1 is the blank top left cell - this should really be
						// outside the scroll to look right
			{
				// tv.setGravity(Gravity.CENTER);
				tv.setText(rows[i]);
			}
			tr.addView(tv);
			tlLeftCol.addView(tr);

			// TableRow trA = new TableRow(this);
			// TextView tvA = new TextView(this);
			// if (i >= 0) // -1 is the blank top left cell - this should really
			// be
			// // outside the scroll to look right
			// {
			// tvA.setText("A" + i);
			// }
			// trA.addView(tvA);
			// trA.setMinimumHeight(ROW_HEIGHT);
			// tlLeftColA.addView(trA);
		}
		lsvLeftCol.addView(tlLeftCol);
		// lsvLeftColA.addView(tlLeftColA);

		// add the main horizontal scroll
		HorizontalScrollView hsvMainContent = new HorizontalScrollView(this);
		hsvMainContent.setHorizontalScrollBarEnabled(false); // you could
																// probably
																// leave this
																// one enabled
																// if you want

		LinearLayout llMainContent = new LinearLayout(this); // Scroll view
																// needs a
																// single child
		llMainContent.setOrientation(LinearLayout.VERTICAL);

		// add the headings +1 +2
		TableLayout tlColHeadings = new TableLayout(this);
		TableRow trHeading = new TableRow(this);
		trHeading.setBackgroundResource(R.color.header_bg);
		// TableRow trHeading1 = new TableRow(this);
		// TableRow trHeading2 = new TableRow(this);
		trHeading.setMinimumHeight(ROW_HEIGHT);
		// trHeading1.setMinimumHeight(ROW_HEIGHT);
		// trHeading2.setMinimumHeight(ROW_HEIGHT);
		for (int i = 0; i < cols.length; i++) {
			TextView tv = new TextView(this);
			tv.setGravity(Gravity.CENTER);
			tv.setText(cols[i]);// numToColumn(i));
			tv.setMinWidth(COL_WIDTH);
			trHeading.addView(tv);

			// TextView tv1 = new TextView(this);
			// tv1.setText(cols[i]);// numToColumn(i));
			// tv1.setMinWidth(COL_WIDTH);
			// trHeading1.addView(tv1);
			//
			// TextView tv2 = new TextView(this);
			// tv2.setText(cols[i]);// numToColumn(i));
			// tv2.setMinWidth(COL_WIDTH);
			// trHeading2.addView(tv2);

		}

		tlColHeadings.addView(trHeading);
		// tlColHeadings.addView(trHeading1);
		// tlColHeadings.addView(trHeading2);
		llMainContent.addView(tlColHeadings);

		// now lets add the main content
		LinkedScrollView lsvMainVertical = new LinkedScrollView(this);
		lsvMainVertical.setLoadMore(true);
		lsvMainVertical.setVerticalScrollBarEnabled(false); // this will not be
															// visible most of
															// the time anyway

		TableLayout tlMainContent = new TableLayout(this);
		// tlMainContent.setStretchAllColumns(true);
		for (int i = 0; i < rows.length; i++) {
			TableRow tr = new TableRow(this);
			if (i % 2 == 0) {
				tr.setBackgroundResource(R.color.cell_dark_bg);
			}
			tr.setMinimumHeight(ROW_HEIGHT);
			for (int j = 0; j < cols.length; j++) {
				EditText et = new EditText(this);
				et.setMinWidth(COL_WIDTH);
				et.setText(data[i][j]);
				et.setImeActionLabel("NEXT", EditorInfo.IME_ACTION_NEXT);
				et.setInputType(InputType.TYPE_CLASS_NUMBER);
				tr.addView(et);
				// TextView tv = new TextView(this);
				// tv.setText(data[i][j]);
				// tv.setMinWidth(COL_WIDTH);
				// tr.addView(tv);
			}
			tlMainContent.addView(tr);
		}

		lsvMainVertical.addView(tlMainContent);

		llMainContent.addView(lsvMainVertical);

		hsvMainContent.addView(llMainContent);

		loading.cancelLoading();
		setContentView(R.layout.activity_main);
		// Set up view
		layout = (LinearLayout) findViewById(R.id.spreadsheet);
		rl_root = (RelativeLayout) findViewById(R.id.rl_root);

		layout.addView(lsvLeftCol);
		layout.addView(hsvMainContent);

		// The magic
		lsvMainVertical.others.add(lsvLeftCol);
		// lsvMainVertical.others.add(lsvLeftColA);

		lsvLeftCol.others.add(lsvMainVertical);
		// lsvLeftCol.others.add(lsvLeftColA);

		// lsvLeftColA.others.add(lsvMainVertical);
		// lsvLeftColA.others.add(lsvLeftCol);
		// loading_bar.setVisibility(View.GONE);

	}

	String numToColumn(int i) {
		boolean go = true;
		String t = "";
		while (go) {
			int x = i % 26;
			String s = "";
			switch (x) {
			case 0:
				s = "Rd";
				break;
			case 1:
				s = "Blk";
				break;
			case 2:
				s = "1xS";
				break;
			case 3:
				s = "2xS";
				break;
			case 4:
				s = "3xS";
				break;
			case 5:
				s = "BBL";
				break;
			case 6:
				s = "TFL";
				break;
			case 7:
				s = "Ard";
				break;
			case 8:
				s = "Abk";
				break;

			case 9:
				s = "Evn";
				break;
			case 10:
				s = "Odd";
				break;
			case 11:
				s = "1xS";
				break;
			case 12:
				s = "2xS";
				break;
			case 13:
				s = "3xS";
				break;
			case 14:
				s = "BBL";
				break;
			case 15:
				s = "FTL";
				break;
			case 16:
				s = "Aod";
				break;

			case 17:
				s = "Big";
				break;
			case 18:
				s = "Sml";
				break;
			case 19:
				s = "1xS";
				break;
			case 20:
				s = "2xS";
				break;
			case 21:
				s = "3xS";
				break;
			case 22:
				s = "BBL";
				break;
			case 23:
				s = "TFL";
				break;
			case 24:
				s = "Abg";
				break;
			case 25:
				s = "Asl";
				break;
			}

			t = s + t;
			if (i < 26)
				go = false;
			i = i / 26;
			i--;
		}
		return t;
	}

	private class LinkedScrollView extends ScrollView {
		public boolean cascadeScroll = true;
		public boolean isLoadMore = false;
		public ArrayList<LinkedScrollView> others = new ArrayList<LinkedScrollView>();

		public LinkedScrollView(Context context) {
			super(context);
		}

		@Override
		protected void onScrollChanged(int l, int t, int oldl, int oldt) {
			super.onScrollChanged(l, t, oldl, oldt);

			if (cascadeScroll) {
				for (int i = 0; i < others.size(); i++) {
					others.get(i).cascadeScroll = false;
					others.get(i).scrollTo(l, t);
					others.get(i).cascadeScroll = true;
				}
			}
			if (isLoadMore) {
				hitBottom(l, t, oldl, oldt);
			}
		}

		private void setLoadMore(boolean isLoadMore) {
			this.isLoadMore = isLoadMore;
		}

		protected void hitBottom(int l, int t, int oldl, int oldt) {
			// Grab the last child placed in the ScrollView, we need it to
			// determinate the bottom position.
			View view = (View) getChildAt(getChildCount() - 1);
			// Calculate the scrolldiff
			int diff = (view.getBottom() - (getHeight() + getScrollY()));
			// if diff is zero, then the bottom has been reached
			if (diff == 0) {
				// notify that we have reached the bottom
				Log.d("", "MyScrollView: Bottom has been reached");
				// Add more button
				addLoadMoreButton();
			}
		}

		private void addLoadMoreButton() {
			final Button bt = new Button(MainActivity.this);
			bt.setText("Load more row");
			RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			rl.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
			bt.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// rl_root.removeViewAt(rl_root.getChildCount()-1);
					rl_root.removeView(bt);
				}
			});
			bt.setLayoutParams(rl);
			rl_root.addView(bt);
		}
	}

	private class LoadingAsyncTask extends AsyncTask<Void, Void, Void> {
		private ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(MainActivity.this);
			dialog.setCancelable(true);
			dialog.setMessage("Loading...");
			dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dialog.show();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			return null;
		}

		public void cancelLoading() {
			dialog.dismiss();
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.btn_save:
			intent = new Intent(getApplicationContext(), DirectoryPicker.class);
			startActivityForResult(intent, DirectoryPicker.PICK_DIRECTORY);
			break;
		case R.id.btn_1:
			intent = new Intent(getApplicationContext(), Graph.class);
			startActivity(intent);
			break;
		case R.id.btn_2:
			intent = new Intent(getApplicationContext(), DEP.class);
			startActivity(intent);
			break;

		default:
			break;
		}

	}
}